package com.example.automanagement.controller;

import com.example.automanagement.util.OcrId;
import com.example.automanagement.util.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@CrossOrigin
@RestController
public class FileUploadController {
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传文件不能为空！";
        }
        try {
            // 假设有一个 MultipartFile 对象名为 file
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀名
            int dotIndex = originalFilename.lastIndexOf(".");
            String fileExtension = originalFilename.substring(dotIndex + 1);
            // 获取当前时间戳
            long timestamp = System.currentTimeMillis();
            // 将时间戳转换为字符串形式
            String timestampStr = Long.toString(timestamp);
            // 将上传文件保存到本地磁盘
            String directoryPath = "D:\\AutoServer\\";
            File directory = new File(directoryPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            String filename = timestampStr + '.' + fileExtension;
            String filePath = directoryPath + filename;
            file.transferTo(new File(filePath));
            // 返回上传文件的url
            String url = "http://localhost:8088" + "/preview/" + filename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传文件失败！";
        }
    }

    @GetMapping("/preview/{filename}")
    public ResponseEntity<Resource> PreviewOrDownload(@PathVariable String filename) {
        try {
            String directoryPath = "D:\\AutoServer\\";
            File file = new File(directoryPath + filename);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }
            Path path = Paths.get(directoryPath, filename);
            Resource resource = new UrlResource(path.toUri());
            HttpHeaders headers = new HttpHeaders();
            String extension = FilenameUtils.getExtension(filename);
            if (extension.equals("png")) {
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE);
            } else if (extension.equals("jpg")) {
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
            } else {
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
            }
            return ResponseEntity.ok().headers(headers).body(resource);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PostMapping("/idUpLoad")
    public Result idUpLoad(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("500", "错误");
        }
        try {
            // 假设有一个 MultipartFile 对象名为 file
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀名
            int dotIndex = originalFilename.lastIndexOf(".");
            String fileExtension = originalFilename.substring(dotIndex + 1);
            // 获取当前时间戳
            long timestamp = System.currentTimeMillis();
            // 将时间戳转换为字符串形式
            String timestampStr = Long.toString(timestamp);
            // 将上传文件保存到本地磁盘
            String directoryPath = "D:\\AutoServer\\";
            File directory = new File(directoryPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            String filename = timestampStr + '.' + fileExtension;
            String filePath = directoryPath + filename;
            file.transferTo(new File(filePath));
            if (filePath == null)
                return Result.error("500", "无效的路径");
            List<String> result = OcrId.sendPost(filePath);
            return Result.success(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
